<template>
	<div class="xMapSelect">
		<div class="xMapSelect-li">
			<f-region ref="x_city_picker" @changePicker="changePicker" @executeOneChange="inputChange" v-model="viewModel.regionId" :requiredFool="true" type="countydroplist" />
		</div>
		<div class="xMapSelect-li">
			<div class="xMapSelect-li_ipt">
				<el-input @blur="blur" class=" address-form" v-model="inputSeacrh" placeholder="请输入地址来直接查找相关位置"></el-input>
			</div>
			<div class="xMapSelect-li_but">搜索地图</div>
		</div>
		<div class="xMapSelect-mapbox">
			<div :id="containerId" class="container-box"></div>
			<div :id="panelId" class="panel-box"></div>
		</div>
	</div>
</template>

<script>
  import { ElNotification } from 'element-plus'
	import MapLoader from './AMap.js'
	const AMap = window.AMap
	export default {
		model: {
			prop: 'dataModel',
			event: 'change'
		},
		props: {
			dataModel: {}
		},
		data() {
			return {
				center: {
					lng: 0,
					lat: 0
				},
				viewModel: {
					regionId: 0,
					address: null,
					longitude: 117.18,
					latitude: 34.27
				},
				zoom: 3,
				addressKeyword: '',
				fullName: null, // 省市区县地址
				inputSeacrh: '',
        containerId: 'container_' + Math.random(),
        panelId: 'panel_' + Math.random()
			}
		},
		mounted() {
			this.drawMap()
			this.init()
		},
		methods: {
			async init() {
        if(this.dataModel) {
          this.viewModel = this.dataModel
        }				
			},
			inputChange(data) {
				this.inputSeacrh = data
				setTimeout(() => {
					var searchBut = document.getElementsByClassName('xMapSelect-li_but')
					searchBut[0].click()
				}, 500)
			},
			drawMap() {
				let that = this
				var geolocation
				var marker
				var placeSearch
				var InfoWindow
				MapLoader().then(AMap => {
					var map = new AMap.Map(that.containerId, {
						resizeEnable: true,
						center: [that.viewModel.longitude, that.viewModel.latitude],
						zoom: 11
					})

					function Geolocation() {
						map.plugin('AMap.Geolocation', function () {
							geolocation = new AMap.Geolocation({
								enableHighAccuracy: true, // 是否使用高精度定位，默认:true
								timeout: 10000, // 超过10秒后停止定位，默认：无穷大
								maximumAge: 0, // 定位结果缓存0毫秒，默认：0
								convert: true, // 自动偏移坐标，偏移后的坐标为高德坐标，默认：true
								showButton: true, // 显示定位按钮，默认：true
								buttonPosition: 'LB', // 定位按钮停靠位置，默认：'LB'，左下角
								buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
								showMarker: true, // 定位成功后在定位到的位置显示点标记，默认：true
								showCircle: true, // 定位成功后用圆圈表示定位精度范围，默认：true
								panToLocation: true, // 定位成功后将定位到的位置作为地图中心点，默认：true
								zoomToAccuracy: true // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
							})
							map.addControl(geolocation)
							geolocation.getCurrentPosition()
							AMap.event.addListener(geolocation, 'complete', (obj) => {
								that.inputSeacrh = obj.formattedAddress
								that.viewModel.address = obj.formattedAddress
								that.viewModel.regionId = obj.addressComponent.adcode
								that.viewModel.longitude = obj.position.lng
								that.viewModel.latitude = obj.position.lat
							}) // 返回定位信息
							AMap.event.addListener(geolocation, 'error', (error) => {
                ElNotification({
                  title: '错误信息',
                  message: error,
                  type: 'error',
                })                
							}) // 返回定位出错信息
						})
					}

					function plugIn() {
						// 同时引入工具条插件，比例尺插件和鹰眼插件
						AMap.plugin([
							'AMap.ToolBar',
							'AMap.Scale',
							'AMap.OverView',
							'AMap.MapType',
							'AMap.Geolocation'
						], function () {
							// 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
							map.addControl(new AMap.ToolBar())

							// 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
							map.addControl(new AMap.Scale())

							// 在图面添加鹰眼控件，在地图右下角显示地图的缩略图
							map.addControl(new AMap.OverView({
								isOpen: true
							}))

							// 在图面添加定位控件，用来获取和展示用户主机所在的经纬度位置
							map.addControl(new AMap.Geolocation())
						})
					}

					function setMaker() {
						marker = new AMap.Marker()
						map.add(marker)
						// 添加解析地理位置插件
						map.plugin('AMap.Geocoder', () => {
							// 异步加载插件
							geolocation = new AMap.Geocoder({
								city: that.fullName, // 默认：“全国”
								radius: 1000 // 范围，默认：500
							})
						})
					}

					function addAmapGeocoder() {
						//为地图注册click事件获取鼠标点击出的经纬度坐标
						map.on('click', function (e) {
							map.remove(marker)
							setMaker()
							const lnglat = [e.lnglat.lng, e.lnglat.lat]
							marker.setPosition(lnglat)
							geolocation.getAddress(lnglat, (status, result) => {
								if (status === 'complete' && result.regeocode) {
                  ElNotification({
                    title: '信息',
                    message: result.regeocode,
                    type: 'error',
                  })
									if (placeSearch !== undefined) {
										placeSearch.clear()
									}
									var info = []
									info.push('<p class="input-item">' + result.regeocode.formattedAddress + '</p>')
									InfoWindow = new AMap.InfoWindow({
										content: info.join('<br>'),
										offset: new AMap.Pixel(0, -40)
									})
									InfoWindow.open(map, [e.lnglat.lng, e.lnglat.lat], map.getCenter())
									that.inputSeacrh = result.regeocode.formattedAddress
									that.viewModel.address = result.regeocode.formattedAddress
									that.viewModel.regionId = result.regeocode.addressComponent.adcode
									that.viewModel.longitude = e.lnglat.lng
									that.viewModel.latitude = e.lnglat.lat
								} else {
									alert(JSON.stringify(result))
								}
							})
						})
					}

					function placeSearchSearch(value = '深圳宝安', city = '010') {
						AMap.service(['AMap.PlaceSearch'], function () {
							//构造地点查询类
							placeSearch = new AMap.PlaceSearch({
								pageSize: 5, // 单页显示结果条数
								pageIndex: 1, // 页码
								city: city, // 兴趣点城市
								citylimit: true, //是否强制限制在设置的城市内搜索
								map: map, // 展现结果的地图实例
								panel: that.panelId, // 结果列表将在此容器中进行展示。
								autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
							})
							//关键字查询
							placeSearch.search(value)
							//搜索列表点击事件
							AMap.event.addListener(placeSearch, 'listElementClick', (e) => {
								var address = e.data.address
								that.inputSeacrh = address
								that.viewModel.address = address
								that.viewModel.regionId = e.data.adcode
								that.viewModel.longitude = e.data.location.lng
								that.viewModel.latitude = e.data.location.lat
							})
							//搜索标记点点击事件
							AMap.event.addListener(placeSearch, 'markerClick', (e) => {
								var address = e.data.address
								that.inputSeacrh = address
								that.viewModel.address = address
								that.viewModel.regionId = e.data.adcode
								that.viewModel.longitude = e.data.location.lng
								that.viewModel.latitude = e.data.location.lat
							})
						})
					}

					Geolocation()
					plugIn()
					setMaker()
					addAmapGeocoder()

					var searchBut = document.getElementsByClassName('xMapSelect-li_but')
					searchBut[0].onclick = function () {
						map.remove(marker)
						if (InfoWindow !== undefined) {
							InfoWindow.close()
						}
						geolocation.getLocation(that.inputSeacrh, function (status, result) {
							if (status === 'complete' && result.geocodes.length) {
								placeSearchSearch(that.inputSeacrh, result.geocodes[0].adcode)
							} else {
                ElNotification({
                  title: '提示',
                  message: '根据地址查询位置失败',
                  type: 'error',
                })
							}
						})
					}
					map.setFitView()
				}, e => {
          ElNotification({
            title: '提示',
            message: '地图加载失败',
            type: 'error',
          })
				})
			},
			// 修改地址
			async changePicker(val) {
				this.fullName = await this.$api.addressFullName(val)
				if (this.fullName) {
					this.addressKeyword = this.fullName + this.viewModel.address
				}
			},
			blur(val) {
				this.addressKeyword = this.fullName + this.viewModel.address
			},
			getLocationPoint(e) {
				this.viewModel.longitude = e.point.lat
				this.viewModel.latitude = e.point.lng
				if (e.overlay && e.overlay.z) {
					this.viewModel.address = e.overlay.z.title
				}
			}
		},
		watch: {
			viewModel: {
				deep: true,
				handler(val) {
					this.$refs.x_city_picker.init()
					this.$emit('change', this.viewModel)
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.xMapSelect {
		.xMapSelect-li {
			margin-bottom: 15px;
			display: flex;
			flex-direction: row;

			.xMapSelect-li_ipt {
				width: 500px;
			}

			.xMapSelect-li_but {
				border: 1px solid #dcdee0;
				margin-left: 10px;
				border-radius: 2px;
				padding: 0 20px;
				font-size: 15px;
				color: #333333;
				cursor: pointer;
        line-height: 32px;
			}

			.xMapSelect-li_but:hover {
				border-color: #3773da;
				color: #3773da;
			}
		}

		.container-box {
			width: 100%;
			height: 500px;
		}

		.custom-input-card {
			width: 18rem;
		}

		.custom-input-card .btn:last-child {
			margin-left: 1rem;
		}

		.content-window-card {
			position: relative;
			width: 23rem;
			padding: 0.75rem 0 0 1.25rem;
			box-shadow: none;
			bottom: 0;
			left: 0;
		}

		.content-window-card p {
			height: 2rem;
		}

		.xMapSelect-mapbox {
			position: relative;
		}

		.panel-box {
			position: absolute;
			background-color: white;
			max-height: 60%;
			overflow-y: auto;
			top: 10px;
			right: 10px;
			width: 280px;
		}
	}
</style>